import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

@Injectable()
export class UploadProxyService {
  private readonly baseUrl: string;

  constructor(private readonly config: ConfigService) {
    this.baseUrl = this.config.get<string>('UPLOADER_BASE_URL', 'http://localhost:8100');
  }

  async uploadSingle(
    file: Express.Multer.File,
    authorization?: string,
  ): Promise<any> {
    const boundary = `----kvboundary${Math.random().toString(16).slice(2)}`;
    const prelude = Buffer.from(
      `--${boundary}\r\n` +
        `Content-Disposition: form-data; name="file"; filename="${escapeQuotes(file.originalname || 'file')}"\r\n` +
        `Content-Type: ${file.mimetype || 'application/octet-stream'}\r\n\r\n`,
      'utf8',
    );
    const closing = Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8');
    const body = Buffer.concat([prelude, file.buffer, closing]);

    const { data } = await axios.post(`${this.baseUrl}/upload/file`, body, {
      headers: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`,
        'Content-Length': body.length,
        ...(authorization ? { Authorization: authorization } : {}),
      },
      maxBodyLength: Infinity,
    });
    return data;
  }

  async uploadMultiple(
    files: Express.Multer.File[],
    authorization?: string,
  ): Promise<any> {
    const boundary = `----kvboundary${Math.random().toString(16).slice(2)}`;
    const parts: Buffer[] = [];
    for (const file of files) {
      parts.push(
        Buffer.from(
          `--${boundary}\r\n` +
            `Content-Disposition: form-data; name="files"; filename="${escapeQuotes(file.originalname || 'file')}"\r\n` +
            `Content-Type: ${file.mimetype || 'application/octet-stream'}\r\n\r\n`,
          'utf8',
        ),
      );
      parts.push(file.buffer);
      parts.push(Buffer.from(`\r\n`, 'utf8'));
    }
    parts.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'));
    const body = Buffer.concat(parts);

    const { data } = await axios.post(`${this.baseUrl}/upload/files`, body, {
      headers: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`,
        'Content-Length': body.length,
        ...(authorization ? { Authorization: authorization } : {}),
      },
      maxBodyLength: Infinity,
    });
    return data;
  }
}

function escapeQuotes(input: string): string {
  return input.replace(/"/g, '\\"');
}


